package com.dog.threesixty;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dog.ui.LearningView;
import com.dog.utils.Constants;
import com.dog.utils.DownloadCompletionListener;
import com.dog.utils.DownloadingItem;
import com.dog.utils.Utils;
import com.inapp.util.BillingService;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class RecallBeforeActivity extends Activity implements OnClickListener {

	private Button backButton;
	private Button startButton;
	private ImageView timeView;
	private ImageView normalView;

	private boolean isTimedClicked;
	private LearningView learnView;
	private int level;

	private boolean isLevelUnlocked[] = new boolean[18];

	private int recallScore[] = new int[18];
	private int percent[] = new int[18];
	private boolean isFilesDownloaded[] = new boolean[18];

	private boolean isTimer;

	private Button quizView;

	private int nextLevel;

	private SharedPreferences sharedPreferences;
	private final OnSharedPreferenceChangeListener ospcl = new OnSharedPreferenceChangeListener() {

		public void onSharedPreferenceChanged(final SharedPreferences sp,
				String key) {
			try {
				if (BillingService.KEY_IN_APP_PURCHASED_ITEM_CHANGED_TIME
						.equals(key)) {
					runOnUiThread(new Runnable() {
						public void run() {
							manageLockedLevels();
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {

			super.onCreate(savedInstanceState);
			setContentView(R.layout.layout_before_recall);

			try {
				sharedPreferences = PreferenceManager
						.getDefaultSharedPreferences(this);
				sharedPreferences
						.registerOnSharedPreferenceChangeListener(ospcl);
			} catch (Exception e) {
				e.printStackTrace();
			}

			backButton = (Button) findViewById(R.id.backButton);
			backButton.setOnClickListener(this);

			startButton = (Button) findViewById(R.id.startButton);
			startButton.setOnClickListener(this);

			quizView = (Button) findViewById(R.id.quizeButton);

			timeView = (ImageView) findViewById(R.id.timedView);
			timeView.setOnClickListener(this);

			normalView = (ImageView) findViewById(R.id.normalView);
			normalView.setOnClickListener(this);

			learnView = (LearningView) findViewById(R.id.learnView);

			nextLevel = getIntent().getIntExtra(Constants.KEY_NEXT_LEVEL, 0);
			if (nextLevel != 0) {
				String message = "";
				String title = "";
				switch (nextLevel) {
				case 4:
				case 5:
				case 6:
				case 7:
					title = "Pack2 need to be purchased";
					message = "Select a Level from Conformation 2,Conformation 3,Conformation 4,Skeleton 1 and press start";
					break;
				case 8:
				case 9:
				case 10:
					title = "Pack3 need to be purchased";
					message = "Select a Level from Skeleton 2,Superficial Muscle 1,Superficial Muscle 2 and press start";
					break;
				case 11:
				case 12:
				case 13:
					title = "Pack4 need to be purchased";
					message = "Select a Level from Deep Muscles 1,Deep Muscles 2,Skull and press start";
					break;

				case 14:
				case 15:
				case 16:
					title = "Pack5 need to be purchased";
					message = "Select a Level from Teeth,Organs 1,Organs 2 and press start";
					break;

				default:
					break;
				}
				Utils.showAlertMessage(RecallBeforeActivity.this, title,
						message);
			}

			manageLockedLevels();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void onDestroy() {
		try {
			if (sharedPreferences != null && ospcl != null) {
				sharedPreferences
						.unregisterOnSharedPreferenceChangeListener(ospcl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private void manageLockedLevels() {
		isLevelUnlocked = Utils.getUnlockedLevels(sharedPreferences);
		String imageFile[] = Utils.getImageFileName(RecallBeforeActivity.this,
				Constants.PACK1_JSON_FILE);
		isFilesDownloaded = Utils.getFilesDownloaded(RecallBeforeActivity.this);
		for (int i = 0; i < 18; i++) {
			recallScore[i] = Utils.getLevelHighestScore(
					RecallBeforeActivity.this, Constants.KEY_RECALL_SCORE + i);
			percent[i] = Utils.getLevelHighestScore(RecallBeforeActivity.this,
					Constants.KEY_RECALL_PERCENTAGE + i);
			Log.i("DREG", "Recall Score = " + recallScore[i]);
		}
		learnView.setLockedLevel(isLevelUnlocked);
		learnView.setScore(recallScore, percent);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent backIntent = new Intent(RecallBeforeActivity.this,
					HomeScreenActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.timedView:
			if (!isTimer) {
				timeView.setImageResource(R.drawable.timed_selected);
				normalView.setImageResource(R.drawable.normal_unselected);
				isTimer = true;
			}
			break;
		case R.id.normalView:
			if (isTimer) {
				timeView.setImageResource(R.drawable.timed_unselected);
				normalView.setImageResource(R.drawable.normal_selected);
				isTimer = false;
			}
			break;
		case R.id.startButton:
			level = LearningView.getSelectedIndex();
			levelWiseOperation(level);
			break;

		case R.id.backButton:
			Intent backIntent = new Intent(RecallBeforeActivity.this,
					HomeScreenActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			break;

		default:
			break;
		}

	}

	private void levelWiseOperation(int level) {

		List<DownloadingItem> downloadingItems = new ArrayList<DownloadingItem>();

		final Intent intent = new Intent(RecallBeforeActivity.this,
				RecallQuizeActivity.class);
		Log.i("DREG", "is Normal=" + isTimer);
		intent.putExtra(Constants.KEY_IS_TIMER, isTimer);
		intent.putExtra(Constants.KEY_LEVEL, level);

		switch (level) {

		// For pack 1
		case 0:
		case 1:
		case 2:
		case 3:
			if (isFilesDownloaded[level]) {
				startActivity(intent);
			} else {
				if (Utils.isDeviceOnline(this)) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK1_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK1_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							RecallBeforeActivity.this,
							Constants.PACK1_JSON_FILE));
					downloadingItems.add(di);
					Utils.downloadFiles(RecallBeforeActivity.this,
							downloadingItems, new DownloadCompletionListener() {

								@Override
								public void onDownloadError(Exception exception) {
									Utils.showAlertMessage(
											RecallBeforeActivity.this, null,
											exception.getMessage());
								}

								@Override
								public void onCompleteDownloading() {
									isFilesDownloaded = Utils
											.getFilesDownloaded(RecallBeforeActivity.this);
									startActivity(intent);
								}
							});
				} else {
					Utils.showAlertMessage(RecallBeforeActivity.this, null,
							"Please go online to download required files.");
				}
			}
			break;

		// For pack 2
		case 4:
		case 5:
		case 6:
		case 7:
			if (!isLevelUnlocked[level]) {
				if (Utils.isDeviceOnline(RecallBeforeActivity.this)) {
					showPurchasePopUp("You must purchase pack 2 to unlock this level");
				} else {
					Toast.makeText(this,
							"\t\tOpps ! !\nNo internet connection",
							Toast.LENGTH_SHORT).show();
				}

			}

			else if (isFilesDownloaded[level]) {
				startActivity(intent);
			} else {
				if (Utils.isDeviceOnline(this)) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK2_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK2_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							RecallBeforeActivity.this,
							Constants.PACK2_JSON_FILE));
					downloadingItems.add(di);
					Utils.downloadFiles(RecallBeforeActivity.this,
							downloadingItems, new DownloadCompletionListener() {

								@Override
								public void onDownloadError(Exception exception) {
									Utils.showAlertMessage(
											RecallBeforeActivity.this, null,
											exception.getMessage());
								}

								@Override
								public void onCompleteDownloading() {
									isFilesDownloaded = Utils
											.getFilesDownloaded(RecallBeforeActivity.this);
									startActivity(intent);
								}
							});
				} else {
					Utils.showAlertMessage(RecallBeforeActivity.this, null,
							"Please go online to download required files.");
				}
			}
			break;

		// For pack 3
		case 8:
		case 9:
		case 10:
			if (!isLevelUnlocked[level]) {
				if (Utils.isDeviceOnline(RecallBeforeActivity.this)) {
					showPurchasePopUp("You must purchase pack 3 to unlock this level");
				} else {
					Toast.makeText(this,
							"\t\tOpps ! !\nNo internet connection",
							Toast.LENGTH_SHORT).show();
				}

			}

			else if (isFilesDownloaded[level]) {
				startActivity(intent);
			} else {
				if (Utils.isDeviceOnline(this)) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK3_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK3_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							RecallBeforeActivity.this,
							Constants.PACK3_JSON_FILE));
					downloadingItems.add(di);
					Utils.downloadFiles(RecallBeforeActivity.this,
							downloadingItems, new DownloadCompletionListener() {

								@Override
								public void onDownloadError(Exception exception) {
									Utils.showAlertMessage(
											RecallBeforeActivity.this, null,
											exception.getMessage());
								}

								@Override
								public void onCompleteDownloading() {
									isFilesDownloaded = Utils
											.getFilesDownloaded(RecallBeforeActivity.this);
									startActivity(intent);
								}
							});
				} else {
					Utils.showAlertMessage(RecallBeforeActivity.this, null,
							"Please go online to download required files.");
				}
			}

			break;

		// For pack 4
		case 11:
		case 12:
		case 13:
			if (!isLevelUnlocked[level]) {
				if (Utils.isDeviceOnline(RecallBeforeActivity.this)) {
					showPurchasePopUp("You must purchase pack 4 to unlock this level");
				} else {
					Toast.makeText(this,
							"\t\tOpps ! !\nNo internet connection",
							Toast.LENGTH_SHORT).show();
				}

			}

			else if (isFilesDownloaded[level]) {
				startActivity(intent);
			} else {
				if (Utils.isDeviceOnline(this)) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK4_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK4_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							RecallBeforeActivity.this,
							Constants.PACK4_JSON_FILE));
					downloadingItems.add(di);
					Utils.downloadFiles(RecallBeforeActivity.this,
							downloadingItems, new DownloadCompletionListener() {

								@Override
								public void onDownloadError(Exception exception) {
									Utils.showAlertMessage(
											RecallBeforeActivity.this, null,
											exception.getMessage());
								}

								@Override
								public void onCompleteDownloading() {
									isFilesDownloaded = Utils
											.getFilesDownloaded(RecallBeforeActivity.this);
									startActivity(intent);
								}
							});
				} else {
					Utils.showAlertMessage(RecallBeforeActivity.this, null,
							"Please go online to download required files.");
				}
			}
			break;

		// For pack 5
		case 14:
		case 15:
		case 16:
			if (!isLevelUnlocked[level]) {
				if (Utils.isDeviceOnline(RecallBeforeActivity.this)) {
					showPurchasePopUp("You must purchase pack 5 to unlock this level");
				} else {
					Toast.makeText(this,
							"\t\tOpps ! !\nNo internet connection",
							Toast.LENGTH_SHORT).show();
				}
			}

			else if (isFilesDownloaded[level]) {
				startActivity(intent);
			} else {
				if (Utils.isDeviceOnline(this)) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK5_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK4_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							RecallBeforeActivity.this,
							Constants.PACK5_JSON_FILE));
					downloadingItems.add(di);
					Utils.downloadFiles(RecallBeforeActivity.this,
							downloadingItems, new DownloadCompletionListener() {

								@Override
								public void onDownloadError(Exception exception) {
									Utils.showAlertMessage(
											RecallBeforeActivity.this, null,
											exception.getMessage());
								}

								@Override
								public void onCompleteDownloading() {
									isFilesDownloaded = Utils
											.getFilesDownloaded(RecallBeforeActivity.this);
									startActivity(intent);
								}
							});
				} else {
					Utils.showAlertMessage(RecallBeforeActivity.this, null,
							"Please go online to download required files.");
				}
			}
			break;

		case 17:
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	private void showPurchasePopUp(String message) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(
				RecallBeforeActivity.this);
		builder.setMessage(message)
				.setCancelable(false)
				.setPositiveButton("Go to store",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
								goTopurchaseScreen();
							}
						})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		final AlertDialog alert = builder.create();
		alert.setTitle("Woof Woof !");
		alert.show();
	}

	private void goTopurchaseScreen() {
		Intent intent = new Intent(RecallBeforeActivity.this,
				PurchaseActivity.class);
		intent.putExtra(Constants.KEY_QUIZ,
				getIntent().getIntExtra(Constants.KEY_QUIZ, 0));
		intent.putExtra(Constants.KEY_LEVEL, level);
		startActivity(intent);
	}

}
